package com.syf.controller;

import com.lmax.disruptor.EventHandler;
import com.syf.disruptor.OrderEvent;
import com.syf.disruptor.OrderEventHandler;
import com.syf.domain.DepthItemVo;
import com.syf.enums.OrderDirection;
import com.syf.feign.OrderBooksFeignClient;
import com.syf.model.MergeOrder;
import com.syf.model.OrderBooks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@RestController
public class MatchController  implements OrderBooksFeignClient {

    @Autowired
    private EventHandler<OrderEvent>[] eventHandlers;  //事件处理器


    /**
     * 测试：【可以在PostMan测试】
     *      localhost:8050/match/order?symbol=BTCGCN&orderDirection=2 (携带Token,若是请求头就必须加上 bearer+ token)
     *      获取交易数据【 OrderEventHandler事件处理器 处理RingBuffer中的订单(交易对、买入1/卖出2)】
     * @param symbol
     * @param orderDirection
     * @return
     */
    @GetMapping("/match/order")
    public TreeMap<BigDecimal, MergeOrder> getTradeData(@RequestParam(required = true) String symbol, @RequestParam(required = true) Integer orderDirection) {
        for (EventHandler<OrderEvent> eventHandler : eventHandlers) {
            OrderEventHandler orderEventHandler = (OrderEventHandler) eventHandler;   //事件处理器 实现类
            //使用 OrderEventHandler事件处理器 处理RingBuffer中的订单(交易对、买入/卖出)
            if (orderEventHandler.getSymbol().equals(symbol)) {
                OrderBooks orderBooks = orderEventHandler.getOrderBooks();
                return orderBooks.getCurrentLimitPrices(OrderDirection.getOrderDirection(orderDirection));
            }
        }
        return null;
    }

    /**
     * 查询该交易对的盘口数据【买入和卖出盘口】
     *      key :sell:asks   value: List<DepthItemVo>
     *      key:buy:bids    value:List<DepthItemVo>
     *
     *      orderEventHandler中 有symbol 和 OrderBooks
     * @param symbol
     * @return
     */
    @Override
    public Map<String, List<DepthItemVo>> querySymbolDepth(String symbol) {
        for (EventHandler<OrderEvent>  eventHandler: eventHandlers) {
            OrderEventHandler orderEventHandler = (OrderEventHandler) eventHandler;  //事件处理器 实现类
            if(orderEventHandler.getSymbol().equals(symbol)){  //获取指定 事件处理器 实现类
                HashMap<String, List<DepthItemVo>> deptMap = new HashMap<>();
                deptMap.put("asks", orderEventHandler.getOrderBooks().getSellTradePlate().getItems());  //卖出盘口数据
                deptMap.put("bids", orderEventHandler.getOrderBooks().getBuyTradePlate().getItems()); //买入盘口数据
                return deptMap;
            }
        }
        return null;
    }

}
